#include "projectsettings.h"
#include "findfiledialog.h"
#include "settings.h"
#include "ui_projectsettings.h"

#include <QFileDialog>

ProjectSettings::ProjectSettings(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ProjectSettings)
{
    ui->setupUi(this);
    ui->serversTable->setColumnWidth(0,200);
    settings = Settings::instance();
    ui->projectPathLine->setText(settings->projectPath());
    ui->serversTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    QStringList servs = settings->serversList();

    for(int i = 0; i < servs.size(); i++) {
        if(servs.at(i).contains(':')) {
            QStringList hostPort = servs.at(i).split(':');
            ui->serversTable->insertRow( i );
            ui->serversTable->setItem(i,0, new QTableWidgetItem(hostPort[0]));
            ui->serversTable->setItem(i,1, new QTableWidgetItem(hostPort[1]));
        }
    }
}

ProjectSettings::~ProjectSettings()
{
    delete ui;
}

void ProjectSettings::on_BrowseButton_clicked()
{
    FindFileDialog w;
    w.exec();
}

void ProjectSettings::done(int res)
{
    if( res == QDialog::Accepted ) {
        settings->setProjectPath( ui->projectPathLine->text() );
        QStringList list;
        for(int i = 0; i < ui->serversTable->rowCount(); i++) {
            QString serv;
            serv += ui->serversTable->item(i,0)->text().toLower() + ":";
            serv += ui->serversTable->item(i,1)->text();
            list.append(serv);
        }
        settings->setServersList(list);
        settings->save();
    }

    QDialog::done(res);
}

void ProjectSettings::on_btnAddServer_clicked()
{
    int row = ui->serversTable->rowCount();
    ui->serversTable->insertRow(row);
    ui->serversTable->setItem(row, 1, new QTableWidgetItem(""));
    ui->serversTable->setItem(row, 1, new QTableWidgetItem(""));
}

void ProjectSettings::on_btnRemoveServer_clicked()
{
    ui->serversTable->removeRow( ui->serversTable->selectionModel()->currentIndex().row() );
}
